# -*- encoding: utf-8 -*-
# @File    : Path.py
# @Date    : 2020/12/28
# @Author  : 韩林新

"""
class
    PathItem
    PathData
"""

from .Control import CtrlId
from .Control import CtrlOp
from .ControlList import ControlList
from .config import input_filename
from .config import gap_line
from .config import outfile
from .config import debug


class PathItem(object):
    """
    遍历路径记录的节点

    Attributs
        ops     控件操作列表
        ctrls   控件id列表(控件id包括type和name)
        no_ctrls没有实现的控件列表
    """

    def __init__(self):
        self.ops = []
        self.ctrls = []
        self.no_ctrls = []

    def add_ops(self, op: CtrlOp):
        """
        增加控件操作
        """
        self.ops.append(op)

    def add_ctrl(self, ctrl: CtrlId):
        """
        增加控件id
        """
        self.ctrls.append(ctrl)

    def check(self, ctrl_lists: ControlList):
        """
        根据控件id列表和Wine环境下的控件对应关系
        """
        for ctrl_id in self.ctrls:
            if not ctrl_lists.has_ctrl(ctrl_id):
                if debug:
                    print("check ctrl ={},+++++".format(ctrl_id))
                    print("not find ctrl ------")
                    ctrl_lists.show_type(ctrl_id.type)
                    print("-----------------------------------")
                self.no_ctrls.append(ctrl_id)
            # else:
                # if debug:
                #     print("find -------")

    def operate(self, ctrl_lists: ControlList):
        """
        根据Windows下的路径在Wine环境下回放
        """
        ret = True
        for op in self.ops:
            if debug:
                print(op)
            ctrl = ctrl_lists.find_by_id(op)
            if ctrl:
                if debug:
                    print("find ")
                if op.op == 'CLICK':
                    ctrl.click()
                elif op.op == 'MOVE':
                    ctrl.move_to()
            else:
                if debug:
                    print("not find")
                ret = False
        return ret

    def show(self):
        for op in self.ops:
            print(op)
        for cl in self.ctrls:
            print(cl)
        print(gap_line)


class PathData(object):
    """
    读取Windows系统下控件遍历路径，结合Wine环境下控件信息获取方法，在Wine环境下回放路径，并在遍历过程中评价控件实现情况
    Attributs

    """

    def __init__(self, filename: str = input_filename):
        """
        docstring
        """
        # print("PathData init")
        # print(filename)
        self.items = []
        self.cur = 0
        self.ctrl_cnt = 0
        self.wrong_cnt = 0
        self.steps = 0
        with open(filename, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            item = PathItem()

            for line in lines:
                # print(line)
                # print(gap_line)
                if line == gap_line:
                    self.items.append(item)
                    self.ctrl_cnt += len(item.ctrls)
                    item = PathItem()
                    self.steps += 1
                    continue
                line = line.strip('\n')
                sec = line.split(',')
                if len(sec) == 2:
                    item.add_ctrl(CtrlId(sec[0], sec[1]))
                elif len(sec) == 3:
                    item.add_ops(CtrlOp(sec[0], sec[1], sec[2]))
                else:
                    raise ValueError("input file has erros!")

    def show(self):
        for item in self.items:
            item.show()
        print("ctrl cnt = {}".format(self.ctrl_cnt))

    def check(self, ctrl_lists):
        if self.cur >= self.steps:
            return False
        if debug:
            print("cur = {}".format(self.cur))
            # print("control List ::")
            # ctrl_lists.show()
        item = self.items[self.cur]
        # if debug:
        #     print("item check:")
        #     item.show()

        item.check(ctrl_lists)
        item.operate(ctrl_lists)
        self.wrong_cnt += len(item.no_ctrls)
        self.cur += 1
        if debug:
            print("sum = {},wrong_cnt = {}\n-------".format(len(item.ctrls),len(item.no_ctrls)))

        return True

    def get_results(self, filename: str = outfile):
        """
        输出遍历过程中的对比结果
        """
        if self.cur < self.steps:
            raise ValueError("not finish the traverse!")
        with open(filename, "w+", encoding='utf-8') as f:
            for item in self.items:
                for ctrl in item.no_ctrls:
                    f.write(ctrl.__str__()+"\n")
